package com.tom.architect02.zframework.viewpager.lazy.fragment;


import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.tom.architect02.R;
import com.tom.architect02.zframework.viewpager.lazy.LazyFragment;

import java.util.ArrayList;

public class Fragment6 extends LazyFragment {
    ViewPager viewPager;
    TabLayout tabLayout;
    ArrayList<LazyFragment> fragments = new ArrayList<>();

    View rootView;

    private int index;

    public Fragment6() {
        fragments.add(new FragmentChild());
        fragments.add(new FragmentChild());
        fragments.add(new FragmentChild());
    }

    @Override
    protected void initView(View rootView) {
        this.rootView = rootView;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_6;
    }

    @Override
    public void loadData() {
        super.loadData();
        viewPager = rootView.findViewById(R.id.fragment_viewPager);
        tabLayout = rootView.findViewById(R.id.fragment_tabLayout);

        FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

        };
        viewPager.setAdapter(fragmentPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                index = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabLayout.getTabAt(0).setText("Tab 1");
        tabLayout.getTabAt(1).setText("Tab 2");
        tabLayout.getTabAt(2).setText("Tab 3");
//        viewPager.setCurrentItem(index);
        viewPager.setOffscreenPageLimit(fragments.size());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
